<template>
  <div class="category-management">
    <AdminTable
      title="分类管理"
      :columns="columns"
      :data="categories"
      :pagination="pagination"
      @create="handleCreate"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="handleSearch"
      @change-page="handleChangePage"
    />
    
    <!-- 分类编辑/创建模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑分类' : '创建分类' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveCategory">
            <div class="form-group">
              <label>分类名称</label>
              <input type="text" v-model="currentCategory.name" required />
            </div>
            <div class="form-group">
              <label>描述</label>
              <textarea v-model="currentCategory.description" rows="3"></textarea>
            </div>
            <div class="form-group">
              <label>排序</label>
              <input type="number" v-model="currentCategory.sort_order" />
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="currentCategory.status">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import AdminTable from '../components/AdminTable.vue'
import { categoryAPI } from '../../../api/index.js'

export default {
  name: 'CategoryList',
  components: {
    AdminTable
  },
  setup() {
    const categories = ref([])
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    const showModal = ref(false)
    const isEditing = ref(false)
    const currentCategory = ref({
      id: null,
      name: '',
      description: '',
      sort_order: 0,
      status: 1
    })
    
    const columns = [
      { key: 'id', title: 'ID' },
      { key: 'name', title: '分类名称' },
      { key: 'description', title: '描述' },
      { key: 'sort_order', title: '排序' },
      { key: 'article_count', title: '文章数' },
      { key: 'create_time', title: '创建时间', type: 'date' },
      { key: 'status', title: '状态', type: 'status' }
    ]
    
    const fetchCategories = async (page = 1, search = '') => {
      try {
        const response = await categoryAPI.getCategories({
          page: page,
          size: pagination.value.size,
          search: search
        })
        
        categories.value = response.data.categories
        pagination.value.total = response.data.total
        pagination.value.page = page
      } catch (error) {
        console.error('Failed to fetch categories:', error)
      }
    }
    
    const handleCreate = () => {
      isEditing.value = false
      currentCategory.value = {
        id: null,
        name: '',
        description: '',
        sort_order: 0,
        status: 1
      }
      showModal.value = true
    }
    
    const handleEdit = (category) => {
      isEditing.value = true
      currentCategory.value = { ...category }
      showModal.value = true
    }
    
    const handleDelete = async (category) => {
      try {
        await categoryAPI.deleteCategory(category.id)
        fetchCategories(pagination.value.page)
      } catch (error) {
        console.error('Failed to delete category:', error)
        alert('删除分类失败')
      }
    }
    
    const handleSearch = (query) => {
      fetchCategories(1, query)
    }
    
    const handleChangePage = (page) => {
      fetchCategories(page)
    }
    
    const saveCategory = async () => {
      try {
        if (isEditing.value) {
          await categoryAPI.updateCategory(currentCategory.value.id, currentCategory.value)
        } else {
          await categoryAPI.createCategory(currentCategory.value)
        }
        closeModal()
        fetchCategories(pagination.value.page)
      } catch (error) {
        console.error('Failed to save category:', error)
        alert('保存分类失败')
      }
    }
    
    const closeModal = () => {
      showModal.value = false
    }
    
    onMounted(() => {
      fetchCategories()
    })
    
    return {
      categories,
      pagination,
      columns,
      showModal,
      isEditing,
      currentCategory,
      handleCreate,
      handleEdit,
      handleDelete,
      handleSearch,
      handleChangePage,
      saveCategory,
      closeModal
    }
  }
}
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #7f8c8d;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #2c3e50;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input[type="number"] {
  width: 100px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>